import { Injectable } from '@nestjs/common';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { DevicePort } from 'src/entities/DevicePort';
import { DevicePortRecord } from 'src/types';
import { ConfigService } from '@nestjs/config';
import { RedisService } from 'src/redis/redis.service';

@Injectable()
export class DevicePortService {
    private devicePortKey:string;
    constructor(
        @InjectRepository(DevicePort) protected repository:Repository<DevicePort>,
        private configService:ConfigService,
        private redis:RedisService,
    ) {
        this.devicePortKey = this.configService.get('redisKey.devicePort')
    }

    async portList(deviceId:number, fields?:(keyof DevicePort)[]) {
        let portList:({[key in keyof DevicePortRecord]? : DevicePortRecord[key]})[] = []
        const cachePort = await this.redis.store.hGetAll(this.devicePortKey + deviceId)
        if(cachePort) {
            for(let k in cachePort) {
                portList.push({portNo : Number(k), status : Number(cachePort[k])})
            }
        }else {
            portList = await this.repository.find({
                where : {
                    deviceId
                },
                select : fields
            })
        }

        

        return portList
    }
}
